package com.fanshuai.controller;

import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Collector;
import io.prometheus.client.exporter.common.TextFormat;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Enumeration;
import java.util.Random;

@RestController
public class CustomController2 {
    private PrometheusMeterRegistry prometheusMeterRegistry;

    private Timer timer;
    private Gauge gauge;
    private Counter counter;
    private DistributionSummary summary;

    private Integer value;

    private Random random = new Random(System.currentTimeMillis());

    @PostConstruct
    public void init() {
        prometheusMeterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);

        timer = Timer.builder("timer")
                .tags()
                .publishPercentiles(0.5, 0.75, 0.9, 0.95, 0.98, 0.99)
                .publishPercentileHistogram(false)
                .register(prometheusMeterRegistry);

        summary = DistributionSummary.builder("summary")
                .publishPercentiles(0.5, 0.75, 0.9, 0.95, 0.98, 0.99)
                .register(prometheusMeterRegistry);

        prometheusMeterRegistry.gauge("gauge", value, Integer::intValue);
        gauge = prometheusMeterRegistry.get("gauge").gauge();

        counter = prometheusMeterRegistry.counter("counter");

        new ClassLoaderMetrics().bindTo(prometheusMeterRegistry);
        new JvmMemoryMetrics().bindTo(prometheusMeterRegistry);
        new JvmGcMetrics().bindTo(prometheusMeterRegistry);
        new ProcessorMetrics().bindTo(prometheusMeterRegistry);
        new JvmThreadMetrics().bindTo(prometheusMeterRegistry);
    }

    @Scheduled(fixedRate = 1000)
    public void schedule() {
        System.out.println("schedule");

        counter.increment();

        timer.record(Duration.ofMillis(random.nextInt(1000)));
        summary.record(random.nextInt(1000));

        value = random.nextInt(10);
    }

    @RequestMapping("/prometheus2")
    public void prometheus2(HttpServletResponse response) throws Exception {
        Enumeration<Collector.MetricFamilySamples> samplesEnumeration = prometheusMeterRegistry.getPrometheusRegistry().metricFamilySamples();
        TextFormat.write004(response.getWriter(), samplesEnumeration);
    }
}
